package com.github.dengmin.mysql.shiro.jwt;

import com.github.dengmin.mysql.shiro.cache.LoginRedisService;
import com.github.dengmin.mysql.shiro.vo.LoginUserVo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author dengmin
 * @Created 2020/8/14 上午10:15
 */
public class JwtRealm extends AuthorizingRealm {
    private static final long serialVersionUID = 1L;

    private LoginRedisService loginRedisService;

    public JwtRealm(LoginRedisService loginRedisService){
        this.loginRedisService = loginRedisService;
    }

    @Override
    public boolean supports(AuthenticationToken token){
        return token != null && token instanceof JwtToken;
    }

    /**
     * 授权认证 设置角色 权限信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        JwtToken jwtToken = (JwtToken) principalCollection.getPrimaryPrincipal();
        String username = jwtToken.getUsername();
        LoginUserVo loginUserRedisVo = loginRedisService.getLoginUserVo(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roleCodes = new HashSet<String>();
        roleCodes.add(loginUserRedisVo.getRoleCode());
        authorizationInfo.setRoles(roleCodes);
        authorizationInfo.setStringPermissions(loginUserRedisVo.getPermissionCodes());
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        if(jwtToken == null){
            throw new AuthenticationException("jwtToken不能为空");
        }
        String salt = jwtToken.getSalt();
        if(StringUtils.isEmpty(salt)){
            throw new AuthenticationException("salt不能为空");
        }
        return new SimpleAuthenticationInfo(jwtToken, salt, getName());
    }
}
